import json
import os

# --- Configuration ---
# List of the specific input JSON files to process
input_files_list = [
    './assets/configs/map/wounded_1001.json',
    './assets/configs/map/wounded_1002.json',
    './assets/configs/map/wounded_1003.json',
    './assets/configs/map/wounded_1004.json',
    './assets/configs/map/wounded_1005.json',
    './assets/configs/map/wounded_1006.json',
    # Add more files here if needed
]

# The desired path for the final combined output JSON file
# Use './' to save in the same directory the script is run from
output_file_path = './combined_map_spawn_points.json'

# --- Filename parsing settings (needed to extract map ID) ---
filename_prefix = 'wounded_'
filename_suffix = '.json'
# --- End Configuration ---


def combine_specific_map_files(file_list, output_path, prefix, suffix):
    """
    Reads a specific list of map JSON files, combines their contents based on map ID
    extracted from filenames, and saves a single aggregated JSON file.

    Args:
        file_list (list): A list of input JSON file paths/names.
        output_path (str): Path to save the combined output JSON file.
        prefix (str): The string part of the filename before the map ID.
        suffix (str): The string part of the filename after the map ID (including '.json').
    """
    # Initialize the final output structure
    final_data = {"map_spawn_points": {}}
    print(f"Processing {len(file_list)} specified files:")

    # Process each file in the list
    for file_path in file_list:
        filename = os.path.basename(file_path)  # Get just the filename
        print(f"  Processing: {file_path}") # Log the full path being attempted

        # --- Step 1: Extract the map ID from the *current* filename ---
        # This block is now correctly INSIDE the loop
        if not filename.startswith(prefix) or not filename.endswith(suffix):
            print(f"    Warning: Skipping file '{filename}' - does not match expected prefix/suffix '{prefix}'...'{suffix}'.")
            continue # Go to the next file_path in the list

        try:
            # Remove prefix and suffix to get the map ID string
            map_id = filename[len(prefix):-len(suffix)]
            if not map_id:
                print(f"    Warning: Skipping file '{filename}' - extracted map ID is empty.")
                continue # Go to the next file_path
            # Optional: You could add int(map_id) here if you need to validate it's numeric
        except Exception as e:
            print(f"    Warning: Error extracting map ID from '{filename}': {e}. Skipping.")
            continue # Go to the next file_path
        # --- End of Step 1 ---

        # --- Step 2: Read the JSON content of the current file ---
        try:
            with open(file_path, 'r', encoding='utf-8') as infile:
                file_content = json.load(infile)
        except FileNotFoundError:
            print(f"    Error: Input file not found at '{file_path}'. Skipping.")
            continue # Go to the next file_path
        except json.JSONDecodeError:
            print(f"    Error: Could not decode JSON from '{filename}'. Check the file format. Skipping.")
            continue # Go to the next file_path
        except Exception as e:
            print(f"    Error reading file '{filename}': {e}. Skipping.")
            continue # Go to the next file_path
        # --- End of Step 2 ---

        # --- Step 3: Combine all spawn points from this file into a single list ---
        combined_spawn_points = []
        if isinstance(file_content, dict):
            for sub_map_key, spawn_list in file_content.items():
                if isinstance(spawn_list, list):
                    combined_spawn_points.extend(spawn_list) # Add all items from sub-list
                else:
                    print(f"    Warning: Expected a list for key '{sub_map_key}' in '{filename}', but found {type(spawn_list)}. Skipping this sub-key.")
        else:
            print(f"    Warning: Expected root element in '{filename}' to be a dictionary, but found {type(file_content)}. Skipping file.")
            continue # Go to the next file_path
        # --- End of Step 3 ---

        # --- Step 4: Add the combined list to the final output structure under the extracted map_id ---
        # Now 'map_id' correctly refers to the ID extracted for the *current* file
        if map_id in final_data["map_spawn_points"]:
            print(f"    Warning: Duplicate map ID '{map_id}' found (from '{filename}'). Overwriting previous data for this ID.")
        final_data["map_spawn_points"][map_id] = combined_spawn_points
        print(f"    Successfully processed map ID '{map_id}' with {len(combined_spawn_points)} spawn points.")
        # --- End of Step 4 ---

    # --- Step 5: Write the final combined data to the output file ---
    if not final_data["map_spawn_points"]:
        print("\nNo valid data was processed. Output file will not be created.")
        return

    try:
        # Ensure the output directory exists (optional, but good practice)
        output_dir = os.path.dirname(output_file_path)
        if output_dir and not os.path.exists(output_dir):
             print(f"Creating output directory: {output_dir}")
             os.makedirs(output_dir)

        print(f"\nSaving combined data to: {output_path}")
        with open(output_path, 'w', encoding='utf-8') as outfile:
            json.dump(final_data, outfile, indent=2, ensure_ascii=False) # indent=2 for pretty print
        print(f"Successfully saved combined data to '{output_path}'")
    except IOError as e:
        print(f"Error: Could not write to output file '{output_path}'. Check permissions or path. Error: {e}")
    except Exception as e:
        print(f"An unexpected error occurred while writing the output file: {e}")
    # --- End of Step 5 ---


# --- Run the combination process ---
if __name__ == "__main__":
    combine_specific_map_files(
        input_files_list,
        output_file_path,
        filename_prefix,
        filename_suffix
    )